<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller {

	protected $model;

	public function __construct(User $user) {
		$this->model = $user;
	}

	//创建一个新的权限角色
	public function store(Request $request) {
		$this->validate($request, [
			'user_id' => 'required|unique:users',
			'is_admin' => 'sometimes|required|numeric',
		]);
		$roles = $request->is_admin ? [] : ($request->roles ?: []);
		$user = $this->model->create($request->only(['user_id', 'is_admin']));
		if ($roles) {
			$user->roles->createMany($roles);
		}
		echo json_encode(['code' => 200, 'msg' => 'success']);
	}

	//更新权限角色
	public function update(Request $request) {
		$this->validate($request, [
			'user_id' => 'required|numeric',
		]);
		$user = $this->model->where('six_id', $request->user_id)->firstOrFail();
		if ($request->is_admin) {
			$user->is_admin = $request->is_admin;
			$user->save();
		}
		$roles = $request->roles ?: [];
		$user->business()->sync($roles);
		echo json_encode(['code' => 200, 'msg' => 'success']);
	}

	//删除权限角色
	public function destroy(Request $request) {
		$this->validate($request, [
			'user_id' => 'required|numeric',
		]);
		$user = $this->model->where('six_id', $request->user_id)->firstOrFail();
		$user->business()->sync([]);
		$user->delete();
		echo json_encode(['code' => 200, 'msg' => 'success']);
	}
}
